package com.vnp.cooking.fragmenthome;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView.ScaleType;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockListFragment;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.viewpagerindicator.CirclePageIndicator;
import com.vnp.cooking.ChinhsuaThongtinActivity;
import com.vnp.cooking.CongthucDaThichActivity;
import com.vnp.cooking.CongthucDadangActivity;
import com.vnp.cooking.ListTenBoSuuTapActivity;
import com.vnp.cooking.LoginActivity;
import com.vnp.cooking.R;
import com.vnp.cooking.ThongbaoActivity;
import com.vnp.cooking.XemThongTinUserActivity;
import com.vnp.cooking.UIcontrols.MyCircleImageView;
import com.vnp.cooking.UIcontrols.MyClickAbleImageView;
import com.vnp.cooking.adapter.CanhanListAdapter;
import com.vnp.cooking.bean.ObjChef;
import com.vnp.cooking.bean.ObjCity;
import com.vnp.cooking.bean.ObjCookpad;
import com.vnp.cooking.fragmentKitchen.CoverCanhan1;
import com.vnp.cooking.fragmentKitchen.CoverCanhan2;
import com.vnp.cooking.httpclient.HttpClientHelper;
import com.vnp.cooking.httpclient.MyJsonHttpResponseHandler;
import com.vnp.cooking.utils.DecodeUtils;
import com.vnp.cooking.utils.HelperListview;
import com.vnp.cooking.utils.PreferenceHelper;
import com.vnp.cooking.utils.Utils;

public class FrgGianbepcuatoi1 extends SherlockListFragment implements
		OnClickListener, OnTouchListener {

	View view;
	CanhanListAdapter adapter;
	ArrayList<ObjCookpad> objCookpads = new ArrayList<ObjCookpad>();
	MyCircleImageView imgAvatar;
	// dialog settings
	ImageButton showDialog;
	Dialog dialog, dH;

	// icon
	MyClickAbleImageView btnDaDang, btnDaThich, btnThongbao, btnHuyhieu,
			btnBanbe, btnDiemthuong;
	DisplayImageOptions options = new DisplayImageOptions.Builder()
			.cacheInMemory(false).cacheOnDisc(true)
			.bitmapConfig(Config.RGB_565).build();

	// xu li cover
	ViewPager pager;
	MyFragmentPagerAdapter myFragmentPagerAdapter;
	CirclePageIndicator indicator;
	PreferenceHelper preferenceHelper;
	
	private int preLast;
	boolean isLoading = false;
	boolean canLoadMore = false;
	
	HashMap<Integer, String> mapCity = new HashMap<Integer, String>();
	ArrayList<ObjCity> objCities = new ArrayList<ObjCity>();
	
	TextView levelUser, cityUser;

	TextView txtNameTitle;
	ObjChef objChef = new ObjChef();

	// load more activity
//	ProgressBar prbLoadActivity;
	ProgressBar progressBarLoadmore;
	
	ProgressBar progressBarLoading;
	Button btnLoadMore;
	View footerMain;
	int mPage = 0;
	Handler mHandler = new Handler();

	Runnable rA = new Runnable() {

		@Override
		public void run() {
			getActivityUser(mPage);
		}
	};
	
	Runnable rInfo = new Runnable() {
		
		@Override
		public void run() {
			getInfoUser();
		}
	};
	
	int totaldadang,totaldathich;
	
	// change avatar
	private static final String TEMP_COVER_FILE = "avatar.jpeg";
	private static final int CHANGE_AVATAR = 1111;
	
	WebView web;
	String urllogout = "http://anuong.net/api/user/logout?user_id=";
	String urlRsLogout = "http://anuong.net/api/user/logout?status";
	ProgressDialog progressDialog;

	TextView txtDadang, txtYeuthich, txtThongbao;

	View actionbar;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = (View) inflater.inflate(R.layout.frg_home_gianbepcuatoi1,
				container, false);
		preferenceHelper = new PreferenceHelper(getActivity());

		actionbar = (View) view.findViewById(R.id.actionbar);

		
		showDialog = (ImageButton) view.findViewById(R.id.btn_settings);
		progressBarLoading = (ProgressBar) view.findViewById(R.id.progressBar1);
//		prbLoadActivity = (ProgressBar) view.findViewById(R.id.prgGetActivity);

		txtNameTitle = (TextView) view.findViewById(R.id.txt_my_name);
		progressBarLoadmore = (ProgressBar) view.findViewById(R.id.progressBar1);
		

		web = (WebView) view.findViewById(R.id.webView);

		getInfoHandler();
		getActivityUserHandler();
		init();
		setFont();

		return view;
	}

	void setFont() {
		txtNameTitle.setTypeface(Utils.getTypefaceRegular(getActivity()),Typeface.BOLD);
	}

	void getActivityUserHandler() {
		mHandler.removeCallbacks(rA);
		mHandler.postDelayed(rA, 300);
	}
	
	private void getInfoHandler() {
		mHandler.removeCallbacks(rInfo);
		mHandler.postDelayed(rInfo, 200);
	}
	
	void addHeader() {
		LayoutInflater inflater = getActivity().getLayoutInflater();
		ViewGroup header = (ViewGroup) inflater.inflate(R.layout.header_acivity, getListView(), false);
		// khai bao cac icon
		btnDaDang = (MyClickAbleImageView) header.findViewById(R.id.btn_dadang);
		txtDadang = (TextView) header.findViewById(R.id.txt_dadang);

		btnDaThich = (MyClickAbleImageView) header.findViewById(R.id.btn_dathich);
		txtYeuthich = (TextView) header.findViewById(R.id.txt_yeuthich);
		
		btnThongbao = (MyClickAbleImageView) header
				.findViewById(R.id.btn_thongbao);
		txtThongbao = (TextView) header.findViewById(R.id.txt_thongbao);
		imgAvatar = (MyCircleImageView) header.findViewById(R.id.img_avatar);
		ImageLoader.getInstance().displayImage(preferenceHelper.getUserUrlAvatar(), imgAvatar, options);
		levelUser = (TextView) header.findViewById(R.id.level_user);
		cityUser = (TextView) header.findViewById(R.id.city_user);
		
		txtYeuthich.setOnClickListener(this);
		btnDaDang.setOnClickListener(this);
		btnDaThich.setOnClickListener(this);
		btnDaDang.setOnClickListener(this);
		btnThongbao.setOnClickListener(this);
		
		levelUser.setTypeface(Utils.getTypefaceRegular(getActivity()), Typeface.BOLD);
		cityUser.setTypeface(Utils.getTypeface(getActivity()), Typeface.BOLD);
		txtYeuthich.setTypeface(Utils.getTypefaceRegular(getActivity()));
		txtDadang.setTypeface(Utils.getTypefaceRegular(getActivity()));
		txtThongbao.setTypeface(Utils.getTypefaceRegular(getActivity()));
		
		ImageLoader.getInstance().displayImage(preferenceHelper.getUserUrlAvatar(), imgAvatar, options);
		levelUser.setText(preferenceHelper.getUserLevelName());
		cityUser.setText(preferenceHelper.getNameCity());
		
		
		imgAvatar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				changeAvatar();
			}
		});
		getListView().addHeaderView(header, null, false);
	}
	

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		addHeader();
		adapter = new CanhanListAdapter(getActivity(), objCookpads);
		getListView().setAdapter(adapter);
//		setListViewHeightBasedOnChildren(getListView());
//		addFooterView();
		loadCacheDataCity();
		
		getListView().setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				int lastItem  = firstVisibleItem + visibleItemCount;
				if (lastItem == totalItemCount){
					if (preLast != lastItem) {
						int last_pos = getListView().getLastVisiblePosition();
						if(last_pos>=objCookpads.size()-1&& !isLoading && (canLoadMore==true)){
							progressBarLoading.setVisibility(View.VISIBLE);
							showDialog.setVisibility(View.GONE);
							getActivityUser(++mPage);
						} else {
							
						}
					} else {
						
					}
				} else {
					
				}
			}
		});
	}

	public void init() {
		txtNameTitle.setText(preferenceHelper.getUserInfoName());
		showDialog.setOnClickListener(this);
		actionbar.setOnClickListener(this);
		
		ImageLoader.getInstance().displayImage(preferenceHelper.getUserUrlAvatar(), imgAvatar, options);
//		levelUser.setText(preferenceHelper.getUserLevelName());
	}

	@Override
	public void onResume() {
		super.onResume();
		txtNameTitle.setText(preferenceHelper.getUserInfoName());
	}

	// dialog settings
	public void showDialogSettings() {
		dialog = new Dialog(getActivity(), R.style.DialogSlideAnim);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_settings);

		// set cac phan tu ben trong
		Button btnEditTk = (Button) dialog.findViewById(R.id.btn_chinhsua_tk);
		Button btnDangxuat = (Button) dialog.findViewById(R.id.btn_dangxuat);
		Button btnThoat = (Button) dialog.findViewById(R.id.btn_thoat);
		
		btnEditTk.setTypeface(Utils.getTypefaceRegular(getActivity()));
		btnDangxuat.setTypeface(Utils.getTypefaceRegular(getActivity()));
		btnThoat.setTypeface(Utils.getTypefaceRegular(getActivity()), Typeface.BOLD);

		WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
		lp.copyFrom(dialog.getWindow().getAttributes());
		lp.width = WindowManager.LayoutParams.MATCH_PARENT;
		lp.height = WindowManager.LayoutParams.WRAP_CONTENT;

		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
		dialog.getWindow().setAttributes(lp);
		dialog.getWindow().setGravity(Gravity.BOTTOM);
		dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));

		// xu li onclick cac nut
		btnEditTk.setOnClickListener(this);
		btnDangxuat.setOnClickListener(this);
		btnThoat.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.actionbar:
			getListView().smoothScrollToPosition(0);
			break;

		case R.id.btn_chinhsua_tk:
			Intent t = new Intent(getActivity(), ChinhsuaThongtinActivity.class);
			dialog.dismiss();
			getActivity().startActivity(t);
			getActivity().overridePendingTransition(R.anim.open_next,
					R.anim.close_main);
			break;
		case R.id.btn_dangxuat:
			progressDialog = ProgressDialog.show(getActivity(), "",
					"Đang thoát...");
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					if (null != progressDialog && progressDialog.isShowing())
						progressDialog.dismiss();
				}
			}, 90000);
			logout();
			dialog.dismiss();
			break;
		case R.id.btn_thoat:
			dialog.dismiss();
			break;
		case R.id.btn_settings:
			showDialogSettings();
			break;
		case R.id.btn_dadang:
			Intent a = new Intent(getActivity(), CongthucDadangActivity.class);
			a.putExtra("userID", preferenceHelper.getID());
			startActivity(a);
			getActivity().overridePendingTransition(R.anim.open_next,
					R.anim.close_main);
			break;
		case R.id.btn_dathich:
			Intent c = new Intent(getActivity(), CongthucDaThichActivity.class);
			c.putExtra("userID", preferenceHelper.getID());
			startActivity(c);
			getActivity().overridePendingTransition(R.anim.open_next,
					R.anim.close_main);
			break;

		case R.id.btn_load_more:
			mPage = mPage + 1;
			progressBarLoadmore.setVisibility(View.VISIBLE);
			btnLoadMore.setText("Đang lấy thêm...");
			getActivityUser(mPage);
			break;
		case R.id.btn_banbe:
			showDialogChuahotro();
			break;
		case R.id.btn_diemthuong:
			showDialogChuahotro();
			break;
		case R.id.btn_huyhieu:
			showDialogChuahotro();
			break;
		case R.id.btn_thongbao:
			gotoThongbao();
			break;
		}
	}

	// show dialog chua ho tro tinh nang
	public void showDialogChuahotro() {
		dH = new Dialog(getActivity(), R.style.DialogSlideAnimLeft);
		dH.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dH.setContentView(R.layout.dialog_chua_hotro);

		// khai bao cac thanh phan
		TextView txtArlert = (TextView) dH.findViewById(R.id.str_canhbao_thoat);
		Button btnDong = (Button) dH.findViewById(R.id.btn_dong);

		btnDong.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dH.dismiss();
			}
		});

		dH.setCanceledOnTouchOutside(true);
		dH.show();
		dH.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		dH.getWindow().setGravity(Gravity.CENTER);
	}
	
	
	void gotoThongbao() {
		Intent t = new Intent(getActivity(), ThongbaoActivity.class);
		startActivity(t);
		getActivity().overridePendingTransition(R.anim.open_next,
				R.anim.close_main);
		
	}
	// xu li phan cover slide
	private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {

		public MyFragmentPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public android.support.v4.app.Fragment getItem(int index) {
			android.support.v4.app.Fragment frg = null;
			switch (index) {
			case 0:
				frg = new CoverCanhan1();
				break;

			case 1:
				frg = new CoverCanhan2();
				break;
			}
			return frg;
		}

		@Override
		public int getCount() {
			return 2;
		}

	}

	// HAM GOI DEN BO SUU TAP
	public void gotoBST() {
		Intent t = new Intent(getActivity(), ListTenBoSuuTapActivity.class);
		startActivity(t);
	}

	// get Data
	public void getInfoUser() {
		HttpClientHelper httpClientHelper = new HttpClientHelper(
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						super.onFailure(error);
					}

					@Override
					public void onSuccess(JSONObject re) {
						try {
							int status = re.getInt("status");
							if (status == 200) {
								JSONObject data = re.getJSONObject("data");

								Log.i("DATA",
										"Thong tin USER: " + data.toString());

								String name = data.getString("name");
								String email = data.getString("email");
								String birth = data.getString("dob");
								String gender = data.getString("gender");
								String levelName = data.getString("level_name");
								String about = data.getString("about");
								int cityID = data.getInt("city_id");
								String userName = data.getString("username");
								String avatar = data.getString("avatar");

								totaldadang = data.getInt("total_created");
								totaldathich = data.getInt("total_favourite");
								Log.i("DATA", "AVATAR :" + avatar);
								
								txtDadang.setText("Đã đăng" + "(" + totaldadang+ ")");
								txtYeuthich.setText("Yêu thích" + "("+ totaldathich + ")");

								preferenceHelper.setUserInfoName(name);
								preferenceHelper.setUserEmail(email);
								preferenceHelper.setUserBirth(birth);
								preferenceHelper.setUserGender(gender);
								preferenceHelper.setUserLevelName(levelName);
								preferenceHelper.setUserAbout(about);
								preferenceHelper.setUserCity(cityID);
								preferenceHelper.setUserURLAvatar(avatar);
								preferenceHelper.setUserName(userName);

								
								// hien thi thanh pho
								Iterator myVeryOwnIterator = mapCity.keySet().iterator();
								while(myVeryOwnIterator.hasNext()) {
								    int key= (Integer) myVeryOwnIterator.next();
								    
								    String value=(String)mapCity.get(key);
								    Log.i("DATA", "Key: "+key+ "Value: "+value);
								    if (key == cityID) {
								    	preferenceHelper.setNameCity(value);
								    	cityUser.setText(""+value);
								    }
								}

								adapter.notifyDataSetChanged();
							} else {

							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

				});
		httpClientHelper.getInfoUser(preferenceHelper.getID());
	}

	public void getActivityUser(final int page) {
		isLoading = true;
		canLoadMore = false;
		HttpClientHelper httpClientHelper = new HttpClientHelper(
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						super.onFailure(error);
						progressBarLoading.setVisibility(View.GONE);
						showDialog.setVisibility(View.VISIBLE);
						isLoading = false;
						Log.i("DATA", "Nhay vao thatbai");
					}

					@Override
					public void onSuccess(JSONObject re) {
						progressBarLoading.setVisibility(View.GONE);
						showDialog.setVisibility(View.VISIBLE);
						isLoading = false;
						Log.i("DATA", "Nhay vao sucess");
						try {
							int status = re.getInt("status");
							if (status == 200) {
								JSONArray data = re.getJSONArray("data");

								Log.i("DATA", "ACIVITY: " + data.toString());
								if(page == 0) {
									adapter.clear();	
								}
								for (int i = 0; i < data.length(); i++) {
									JSONObject jo = data.getJSONObject(i);
									JSONObject tacgia = jo
											.getJSONObject("author");

									ObjCookpad objCookpad = new ObjCookpad();
									objCookpad.setId(jo.getString("id"));
									objCookpad
											.setNamePersonCookpad(preferenceHelper
													.getUserInfoName());
									objCookpad.setDescriptionCookpad(jo
											.getString("desc"));
									objCookpad.setUrlAvatar(preferenceHelper
											.getUserUrlAvatar());
									objCookpad.setNameCookpad(jo
											.getString("name"));
									// getImage
									JSONObject image = jo
											.getJSONObject("image");
									objCookpad.setUrlImageCookpad(image
											.getString("cover"));

									objCookpad.setThoigianNauan(jo
											.getString("time"));
									objCookpad.setCreatedDateCookpad(jo
											.getString("created_action"));
									objCookpad.setAction(jo.getString("action"));
									objCookpad.setViewedCookpad(jo
											.getInt("view_count"));
									objCookpad.setLikeCookpad(jo
											.getInt("like_count"));

									objCookpad.setIdNamePerson(tacgia
											.getString("id"));
									objCookpad.setNamePersonCookpad(tacgia
											.getString("name"));

									objCookpads.add(objCookpad);

								}
								if (data.length() == 10) {
//									footerMain.setVisibility(View.VISIBLE);
									canLoadMore = true;
								} else {
									canLoadMore = false;
								}

								adapter.notifyDataSetChanged();

								
							} else {

							}

						} catch (JSONException e) {
							e.printStackTrace();
							showDialog.setVisibility(View.VISIBLE);
							progressBarLoading.setVisibility(View.GONE);
						}
					}

				});
		httpClientHelper.getInfoActivity(preferenceHelper.getID(), page);
	}

	// logout
	void logout() {
		web.setWebViewClient(new MyWebViewClient());
		Log.i("DATA", ""+urllogout+preferenceHelper.getID());
		web.loadUrl(urllogout+preferenceHelper.getID());
	}

	private class MyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, final String url) {
			view.loadUrl(url);
			return true;
		}

		@Override
		public void onPageStarted(WebView view, final String url, Bitmap favicon) {
			if (url.startsWith(urlRsLogout)) {
				Thread tr = new Thread() {

					@Override
					public void run() {
						String str = "";
						HttpResponse response;
						HttpClient myClient = new DefaultHttpClient();
						HttpPost myConnection = new HttpPost(url);
						Log.i("DATA", "--------------1");
						try {
							response = myClient.execute(myConnection);
							Log.i("DATA", "--------------2");
							str = EntityUtils.toString(response.getEntity(),
									"UTF-8");
							Log.i("DATA", "DATA CHUA PASER: " + str);
						} catch (ClientProtocolException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}

						try {
							JSONObject jo = new JSONObject(str);

							int status = jo.getInt("status");
							if (status == 200) {

								Intent t = new Intent(getActivity(),
										LoginActivity.class);
								getActivity().finish();
								t.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
								startActivity(t);
								preferenceHelper.setID("");
								progressDialog.dismiss();

							} else {
								progressDialog.dismiss();
								Toast.makeText(getActivity(),
										"Thoát thất bại.", Toast.LENGTH_SHORT)
										.show();
							}
							/*
							 * preferenceHelper.setID(userID);
							 * preferenceHelper.setUserInfoName
							 * (data.getString("name"));
							 * preferenceHelper.setUserEmail
							 * (data.getString("email"));
							 * preferenceHelper.setUserURLAvatar
							 * (data.getString("avatar"));
							 * preferenceHelper.setUserBirth
							 * (data.getString("dob"));
							 * preferenceHelper.setUserGender
							 * (data.getString("gender"));
							 * preferenceHelper.setUserAbout
							 * (data.getString("about"));
							 * preferenceHelper.setUserName
							 * (data.getString("username")); //
							 * preferenceHelper.
							 * setUserCity(data.getInt("city_id"));
							 */
						}

						catch (JSONException e) {
							e.printStackTrace();
						}
					}

				};
				tr.start();

			}
		}
	}

	void addFooterView() {
		View loadMoreView = ((LayoutInflater) this.getActivity()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
				R.layout.footer_loadmore, null, false);
		footerMain = (View) loadMoreView.findViewById(R.id.footer_main);
		footerMain.setVisibility(View.GONE);
		getListView().addFooterView(loadMoreView);
		btnLoadMore = (Button) loadMoreView.findViewById(R.id.btn_load_more);
		progressBarLoadmore = (ProgressBar) loadMoreView
				.findViewById(R.id.progressBar1);
		btnLoadMore.setOnClickListener(this);
	}

	public void setListViewHeightBasedOnChildren(ListView listView) {
		ArrayAdapter listAdapter = (ArrayAdapter) listView.getAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}

		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
		listView.requestLayout();
	}
	
	void loadCacheDataCity() {
		String cache = preferenceHelper.getDataFilter();
		if(!cache.equals("")) {
			try {
				JSONObject response = new JSONObject(cache);
				parseData(response);
			} catch (Exception e) { }
		}
	}
	
	public void parseData(JSONObject re) {
		try {
			int status = re.getInt("status");
			if (status == 200) {
				JSONObject data = re.getJSONObject("data");
				JSONArray cities = data.getJSONArray("city");
				for (int i = 0; i < cities.length(); i++) {
					JSONObject city = cities.getJSONObject(i);
					ObjCity objCity = new ObjCity();
					objCity.setId(city.getInt("id"));
					objCity.setName(city.getString("name"));
					objCities.add(objCity);
					
					int key = city.getInt("id");
					String value = city.getString("name");
					mapCity.put(key, value);
				}
			} else {
				Toast.makeText(getActivity(), "Không lấy được dữ liệu",  Toast.LENGTH_SHORT).show();
			}
		} catch (JSONException e) {
			e.printStackTrace();
			Toast.makeText(getActivity(), "Không lấy được dữ liệu",  Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.img_avatar:
			if (event.getAction() == MotionEvent.ACTION_UP){
				changeAvatar();
			}
			break;

		default:
			break;
		}
		return false;
	}
	
	public void changeAvatar() {
		Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		i.setType("image/*");
		startActivityForResult(i, CHANGE_AVATAR);
		
	}
	
	

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.i("DATA", "Nhay vao result ben ngoai--------------");
		 android.support.v4.app.Fragment fragment = getFragmentManager().findFragmentByTag("KEY_CONTENT");
	      if(fragment != null){
	            fragment.onActivityResult(requestCode, resultCode, data);
	      } else {
	    	  Toast.makeText(getActivity(), "Bạn chưa chọn ảnh", Toast.LENGTH_SHORT).show();
		}
		if (data != null && resultCode == Activity.RESULT_OK && requestCode == CHANGE_AVATAR) {
			Log.i("DATA", "Nhay vao result ben trong--------------");
				onChangeAvatar(requestCode, resultCode, data);
		} else {
			Toast.makeText(getActivity(), "Bạn chưa chọn ảnh", Toast.LENGTH_SHORT).show();
		}
	}
	
	
	// change avatar
		void onChangeAvatar(int requestCode, int resultCode, Intent data) {
			Log.i("DATA", "Nhay vao day--------------");
			Uri u = (Uri) data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };
			Cursor cursor = getActivity().getContentResolver().query(u, filePathColumn, null, null, null);
			cursor.moveToFirst();
			int columnIndex        = cursor.getColumnIndex(filePathColumn[0]);
			final String file_path = cursor.getString(columnIndex);
			
			 // bimatp factory
			Bitmap bm = DecodeUtils.decode(getActivity(), Uri.parse(file_path), 800, 800);
			imgAvatar.setScaleType(ScaleType.CENTER_CROP);
			imgAvatar.setImageBitmap(bm);
			
			// xu li phan upload tai day
			RequestParams params = new RequestParams();
			params.put("user_id", preferenceHelper.getID());
			try {
				params.put("fileUpload", new File(file_path));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			
			AsyncHttpClient client = new AsyncHttpClient();
			client.post("http://anuong.net/api/user/avatar", params, new MyJsonHttpResponseHandler(){

				@Override
				public void onFailure(Throwable error) {
					// TODO Auto-generated method stub
					super.onFailure(error);
				}
				

				@Override
				public void onSuccess(JSONObject re) {
					try {
						int status = re.getInt("status");
						switch (status) {
						case 200:
							JSONObject data = re.getJSONObject("data");
							String avatar = data.getString("url");
							Log.i("DATA", "Avatar: "+avatar);
							preferenceHelper.setUserURLAvatar(avatar);
							Log.i("DATA", "THanh cong");
							break;
						case 400:
							Log.i("DATA", "Thieu truong");
							break;
						case 404:
							Log.i("DATA", "ID khong chuan");
							break;

						default:
							break;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
					
				}
				
			});
			
			
			cursor.close();
		}
	
	

}
